package com.appspot.moviesessions.provider;

import java.util.ArrayList;
import java.util.List;

public class QuerySpecification {

	String table;

	List<String> columns = new ArrayList<String>();

	String selection;

	List<String> selectionArgs = new ArrayList<String>();

	String groupBy;

	String having;

	String orderBy;

	public static QuerySpecificationBuilder forTable(String table) {
		return new QuerySpecificationBuilder(table);
	}

	public static class QuerySpecificationBuilder {

		private static final String[] EMPTY_ARRAY = new String[0];
		private QuerySpecification spec;

		public QuerySpecificationBuilder(String table) {
			spec = new QuerySpecification();
			spec.table = table;
		}

		public QuerySpecificationBuilder column(String col) {
			spec.columns.add(col);
			return this;
		}

		public QuerySpecificationBuilder columns(String[] projection) {
			for (String col : safe(projection)) {
				column(col);
			}
			return this;
		}

		public QuerySpecificationBuilder selection(String where) {
			spec.selection = where;
			return this;
		}

		public QuerySpecification build() {
			return spec;
		}

		public QuerySpecificationBuilder selectionArg(String whereArg) {
			spec.selectionArgs.add(whereArg);
			return this;

		}

		public QuerySpecificationBuilder selectionArgs(String[] whereArgs) {
			for (String whereArg : safe(whereArgs)) {
				selectionArg(whereArg);
			}
			return this;
		}

		public static String[] safe(String[] arr) {
			return (arr == null) ? EMPTY_ARRAY : arr;
		}

		public QuerySpecificationBuilder sortOrder(String sortOrder) {
			spec.orderBy = sortOrder;
			return this;
		}

	}

	public String[] getColumns() {
		return columns.toArray(new String[0]);
	}

	public String[] getSelectionArgs() {
		return selectionArgs.toArray(new String[0]);
	}

}
